
float timeStartGame;
int state = 0; // 0 = intro; 1 = main menu; 2 = options; 3 = ingame; 4 = GAME OVER; 5 = instructions
int nstates = 6;
var fctDraw = { drawIntro, drawMainMenu, drawOptions, drawInGame, drawGameOver, drawInstructions };
var fctKeyPressed = { keyPressedIntro, keyPressedMainMenu, keyPressedOptions, keyPressedInGame, keyPressedGameOver, keyPressedInstructions };
int justCameIn = 1;
int vision = 1; // 0 = OFF; 1 = ON normal; 2 = ON horizontal
int volume = 3; //0 = mute; 5 = max;
int screenWidth = 800;
int screenHeight = 800;

Array.prototype.remove = function ( s )
{
	var i = this.indexOf ( s );
	if ( i != -1 )
		this.splice ( i, 1 );
};
void println(v){}

void setup()
{
        timeStartGame = millis ();
        size(screenWidth,screenHeight);
        //noLoop();
        PFont fontA = loadFont("courier");
        textFont(fontA, 14);
        
        int channel_max = 10; // number of channels
        audiochannels = new Array ();
        for ( a = 0; a < channel_max; ++a )
        { // prepare the channels
                audiochannels[a] = new Array();
                audiochannels[a]['channel'] = new Audio(); // create a new audio object
                audiochannels[a]['finished'] = -1; // expected end time for this channel
        }
}
  
void draw()
{
        if ( state < 0 || state >= nstates )
                state = 0;
        if ( fctDraw[state] != null )
			fctDraw[state] ();
}

void keyPressed ()
{
        if ( state < 0 || state >= nstates )
                state = 0;
        if ( fctKeyPressed[state] != null )
			fctKeyPressed[state] ();
}

Audio play_multi_sound ( id )
{
	if ( !document.getElementById(id) )
	{
		println("no such id: " + id);
		return;
	}
        for ( a = 0; a < audiochannels.length; ++a )
        {
                thistime = new Date();
                if (audiochannels[a]['finished'] < thistime.getTime())
                { // is this channel finished?
                        audiochannels[a]['finished'] = thistime.getTime() + document.getElementById(id).duration*1000;
                        audiochannels[a]['channel'].src = document.getElementById(id).src;
                        audiochannels[a]['channel'].load();
						audiochannels[a]['channel'].volume=1/5*volume;
                        audiochannels[a]['channel'].play();
                        return audiochannels[a];
                }
        }
}


void stop_multi_sound_by_id ( id )
{
	if ( !document.getElementById(id) )
	{
		println("no such id: " + id);
		return;
	}
	for ( a = 0; a < audiochannels.length; ++a )
	{
		if ( audiochannels[a]['channel'].src == document.getElementById(id).src )
		{
			audiochannels[a]['channel'].pause();
			audiochannels[a]['finished'] = -1;
			break;
		}
	}
}

void stop_multi_sound ( o )
{
	if ( !o )
	{
		println("no such object: " + o);
		return;
	}
	o['channel'].pause();
	o['finished'] = -1;
}

